//
//  NSData+Crc16.m
//  xy_hehu
//
//  Created by pac on 2019/4/22.
//  Copyright © 2019 pac. All rights reserved.
//

#import "NSData+Crc16.h"

@implementation NSData (Crc16)

- (NSString *)hexadecimalString
{
    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
    
    if (!dataBuffer)
    {
        return [NSString string];
    }
    
    NSUInteger          dataLength  = [self length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i)
    {
        [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }
    
    return [NSString stringWithString:hexString];//此时校验码是相反的，需要互换位置才可以。另外写一个方法
}

- (NSData*)crc16 {
    const uint8_t *byte = (const uint8_t *)self.bytes;
    uint16_t length = (uint16_t)self.length;
    uint16_t res =  getCRC16(byte, length);
    
    NSData *val = [NSData dataWithBytes:&res length:sizeof(res)];
    
    return val;
}

unsigned short getCRC16(unsigned char *ptr,unsigned char len)
{
    unsigned char i;
    unsigned short crc = 0xFFFF;
    if(len==0)
    {
        len = 1;
    }
    while(len--)
    {
        crc ^= *ptr;
        for(i=0; i<8; i++)
        {
            if(crc&1)
            {
                crc >>= 1;
                crc ^= 0xA001;
            }
            else
            {
                crc >>= 1;
            }
        }
        ptr++;
    }
    return(crc);
}


@end
